package org.lanyu.springainovel.common.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.util.ConversionUtil;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * mcp连接配置的json分为两种类型，分别是sse和STDIO，json格式分别如下�? * sse
 *{
 * "mcpServers": {
 * "sse-server": {
 * "type": "sse",
 * "url": "https://mcp.example.com/sse",
 * "headers": {
 * "Authorization": "Bearer your_token",
 * "Content-Type": "application/json"
 * },
 * "reconnectInterval": 5000
 * }
 * }
 * }
 * STDIO
 * {
 * "mcpServers": {
 * "stdio-server": {
 * "type": "stdio",
 * "command": ["python3", "/path/to/mcp_bridge.py"],
 * "workingDirectory": "/tmp",
 * "env": {
 * "MCP_KEY": "your_api_key"
 * }
 * }
 * }
 * }
 *
 */
@Slf4j
@Data
@TableName("ai_mcp")
public class AiMcp {
    public AiMcp() {
        super();
    }
    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField("content_type")
    @Schema(description = "mcp服务器连接类型，sse、STDIO")
    private String contentType;

    @TableField("name")
    private String name;

    @TableField("description")
    private String description;

    @TableField("config_json")
    @Schema(description = "mcp配置JSON")
    private String configJson;

    @TableField("status")
    @Schema(description = "服务状态（实时检查更新）1可用0不可用")
    private Integer status;

    @TableField("enable")
    @Schema(description = "服务启用状态，1启用�?禁用")
    private Integer enable;

    @TableField("update_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Timestamp updateTime;


    public Map<String, ServerConfig> parseServerConfigs() {
        Map<String, ServerConfig> result = new HashMap<>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode root = objectMapper.readTree(this.configJson);
            JsonNode serversNode = root.path("mcpServers");
            if (serversNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> fields = serversNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    String serverName = entry.getKey();
                    JsonNode serverNode = entry.getValue();
                    String type = serverNode.path("type").asText("");
                    ServerConfig config = ConversionUtil.parseServerConfigFromJson(serverName, serverNode, type);
                    if (config != null) {
                        result.put(serverName, config);
                    }
                }
            }
        } catch (Exception e) {
            log.error("转换ServerConfig失败");
        }
        return result;
    }
}
